package cn.hinglo.gameclaw.admin.service;

import cn.hinglo.gameclaw.admin.dao.VersionDao;
import cn.hinglo.gameclaw.data.utils.CommonUtils;
import cn.hinglo.gameclaw.data.utils.FieldUtils;
import cn.hinglo.gameclaw.data.utils.FileImageUtils;
import cn.hinglo.gameclaw.user.bean.Version;
import com.gitee.hinglo.apkinfo.ApkUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @createTime: 2018/6/4
 * @author: HingLo
 * @description: 版本管理的服务层
 */
@Service
@CacheConfig(cacheNames = "version")
public class VersionService {

    @Autowired
    private VersionDao versionDao;

    /**
     * 查询全部的版本集合
     *
     * @return 返回集合列表
     */
    @Cacheable
    public List<Version> listService() {
        return versionDao.selectAll();
    }

    @CacheEvict(allEntries = true, condition = "#result==true")
    public boolean addService(MultipartFile apk, String content) {
        Version version = new Version().setDate(new Date()).setContent(content);
        String suffix = FileImageUtils.getSuffixUtils(apk);
        boolean bool = FileImageUtils.suffixUtils(suffix, ".apk", ".ipa");
        if (!bool) {
            return false;
        }
        //生成文件名称
        String fileName = System.currentTimeMillis() + suffix;
        version.setName(fileName);
        //获取软件保存的路径
        String path = FileImageUtils.readUrlUtils(FieldUtils.IMAGE_8);
        try {
            //写入软件到本地文件中
            if (CommonUtils.convertInputStreamToFileUtils(apk.getBytes(), path, fileName)) {
                Map<String, Object> map = getVersion(suffix, path + fileName);
                version.setNum(map.get("versionName").toString());
                version.setMd5(map.get("md5").toString());
                version.setSize(Double.valueOf(map.get("size").toString()));
                return versionDao.insert(version) == 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 用于获取文件后缀
     *
     * @param suffix
     * @param path
     * @return
     */
    private Map<String, Object> getVersion(String suffix, String path) {
        if (suffix.equalsIgnoreCase(".apk")) {
            return ApkUtil.getApkInfoUtils(path);
        } else {
            //ios 获取软件信息
            return null;
        }
    }
}
